odoo.define('web_ps_report.PsReportController', function (require) {
    'use strict';

    var AbstractController = require('web.AbstractController');
    var core = require('web.core');
    var qweb = core.qweb;
    var _lt = core._t;

    //canavas页面元素
    var cDg;

    var PsReportController = AbstractController.extend({
        custom_events: _.extend({}, AbstractController.prototype.custom_events, {
            'row_clicked': '_onRowClicked',
            'search_clicked': '_onSearchButtonClicked',
            'download_clicked': '_onDownloadButtonClicked',
            'print_clicked': '_onPrintButtonClicked',
            'collection_clicked': '_onCollectionButtonClicked',
            'show_detail_clicked': '_onShowDetailButtonClicked',
            'table_td_clicked': '_onshowClickDetail',
        }),

        _onshowClickDetail: function(event){
            this.do_action(event.data.result)
        },
        /**
         * @override
         * @param {Widget} parent
         * @param {PsReportModel} model
         * @param {PsReportRenderer} renderer
         * @param {Object} params
         * @param {string} params.modelName
         * @param {string} params.title
         * @param {Object} params.measures
         * @param {Object} params.intervals
         * @param {string} params.dateStartString
         * @param {string} params.dateStopString
         * @param {string} params.timeline
         * @param {Array[]} params.views
         */
        init: function (parent, model, renderer, params) {
            this._super.apply(this, arguments);
            this.model = model;
            this.title = params.title;
            this.measures = params.measures;
            this.intervals = params.intervals;
            this.dateStartString = params.dateStartString;
            this.dateStopString = params.dateStopString;
            this.timeline = params.timeline;
            this.views = params.views;
            this.render_type = params.render_type;
            this.ps_fields = params.ps_fields;
            this.renderer.model = model;
            this.modelName = params.modelName;
        },


        //--------------------------------------------------------------------------
        // Public
        //--------------------------------------------------------------------------

        /**
         * Returns the current mode, measure and groupbys, so we can restore the
         * view when we save the current state in the search view, or when we add it
         * to the dashboard.
         *
         * @override
         * @returns {Object}
         */
        getContext: function () {
            var state = this.model.get();
            return {
                cohort_measure: state.measure,
                cohort_interval: state.interval,
            };
        },

        //--------------------------------------------------------------------------
        // Private
        //--------------------------------------------------------------------------

        /**
         * @private
         * @param {string} interval
         */
        _setInterval: function (interval) {
            this.update({interval: interval});
        },
        /**
         * @private
         * @param {string} measure should be a valid (and aggregatable) field name
         */
        _setMeasure: function (measure) {
            this.update({measure: measure});
        },
        /**
         * @override
         * @private
         * @returns {Deferred}
         */
        _update: function () {
            // this._updateButtons();
            // AAB: update the control panel -> this will be moved elsewhere at some point
            var cpContent = _.extend({}, this.controlPanelElements);
            if (this.searchView) {
                _.extend(cpContent, {
                    // $searchview: this.searchView.$el,
                    // $searchview_buttons: this.searchView.$buttons,
                });
            }
            this.update_control_panel({
                active_view_selector: '.o_cp_switch_' + this.viewType,
                cp_content: cpContent,
                hidden: !this.withControlPanel,
                searchview: this.searchView,
                search_view_hidden: !this.searchable || this.searchviewHidden,
                groupable: this.groupable,
                enableTimeRangeMenu: this.enableTimeRangeMenu,
            });

            this._pushState();
            return this._renderBanner();
        },


        //--------------------------------------------------------------------------
        // Handlers
        //--------------------------------------------------------------------------

        /**
         * Do what need to be done when a button from the control panel is clicked.
         *
         * @private
         * @param {MouseEvent} ev
         */
        _onButtonClick: function (ev) {
            var $btn = $(ev.currentTarget);
            //绑定fa-search事件
            if ($btn.hasClass('o_search_psreport')) {
                this.reload($btn.data('interval'));
            }

            if ($btn.hasClass('o_ps_report_interval_button')) {
                this._setInterval($btn.data('interval'));
            } else if ($btn.hasClass('o_cohort_download_button')) {
                this._downloadExcel();
            } else if ($btn.closest('.o_cohort_measures_list').length) {
                ev.preventDefault();
                ev.stopPropagation();
                this._setMeasure($btn.data('field'));
            }
        },

        _onShowDetailButtonClicked: function (event) {
            //显示明细行
            //修改显示控制值，重新渲染tableview
            this.renderer.show_detail_control = !this.renderer.show_detail_control;
            var $table = qweb.render('PsReportViewTableData', {
                report: this.model.psdata.report,
                render_type: this.renderer.arch.attrs.render_type,
                is_show_detail_control: this.renderer.show_detail_control,
            })
            this.$el.find('#table-div').replaceWith($table);

        },

        /***
         *点击收藏按钮，存储当前所定义的筛选条件。以便下次初始化当前默认条件
         * @private
         */
        _onCollectionButtonClicked: function () {
            var result = [
                this._rpc({
                    model: 'ps.save.search_data',
                    method: 'save_search_data',
                    kwargs: {
                        model_name: this.modelName,
                        json_data: JSON.stringify(this.model.set_search_domian())
                    }
                }).then(function (result) {
                    if (result > 0) {
                        alert("收藏成功")
                    }
                })];

        },


        /***
         *
         * @private
         */
        _onSearchButtonClicked: function () {
            var render_type = $('#render_type').val();

            var render_type = this.renderer.render_type || this.render_type || render_type;
            if (render_type == 'table' || render_type == 'qweb') {
                this._onSearchButtonClickedTable()
            }
            if (render_type == 'sheetjs') {
                this._onSearchButtonClickedSheetJS()
            }

        },


        /***
         *
         * @param event
         * @private
         */
        // 导出为Excel功能
        _onDownloadButtonClicked: function (event) {

            var render_type = $('#render_type').val();

            var render_type = this.renderer.render_type || this.render_type || render_type;
            if (render_type == 'table') {
                this._onDownloadButtonClickedExcel()
            }

            if (render_type == 'sheetjs') {
                this._onDownloadButtonClickedSheetJs()
            }

        },

        _onPrintButtonClicked: function (event) {
            if (this.renderer.render_type == 'sheetjs') {
                this._onPrintButtonClickedSheetJs(event)
            } else if (this.renderer.render_type == 'table') {
                this._onPrintButtonClickedTable(event)
            }
        },


        _onSearchButtonClickedTable: function (event) {
            var self = this;
            this.model._fetchData().then(function () {
                var $table = qweb.render('PsReportViewTableData', {
                    report: self.model.psdata.report,
                    render_type: self.renderer.arch.attrs.render_type,
                    is_show_detail_control: self.renderer.show_detail_control,
                });
                self.$el.find('#table-div').replaceWith($table);
                if (self.model.psdata.report.thead_hidden) {
                    self.$el.find('#table-div').find('table').stickyTableHeaders({
                        scrollableArea: $(".o_content")[0],
                        fixedOffset: 0.1
                    })
                }

                // 让部分表格单元呈现可点击状态
//                var tr_length = $('table:eq(1)>tbody:eq(1)>tr:eq(0)>td').length;
//                var amountIndex;
//                if (tr_length === 10) {
//                    amountIndex = 1;
//                } else if (tr_length === 11) {
//                    amountIndex = 2;
//                };
//                var linkable_tds = $('table:eq(1)>tbody:eq(1)>tr')
//                _.each(linkable_tds, function(item){
//                    var items = $(item).find('td:gt('+amountIndex+')');
//                    _.each(items, function(td_node){
//                        var node = $(td_node);
//                        node.html('<a href="#">'+ node.html() + '</a>')
//                    })
//                })
            });
        },


        _onSearchButtonClickedSheetJS: function (event) {
            //canavas页面元素
            var cDgtemp;
            //如果渲染类型是sheetjs类型
            var self = this;
            this.model._fetchData().then(function () {
                var data = self.model.psdata.report;
                document.getElementById('htmlout').innerHTML = "";
                var HTMLOUT = document.getElementById('htmlout');
                cDgtemp = canvasDatagrid({
                    parentNode: HTMLOUT,
                    editable: false,
                    data: data.content_data,
                    schema: data.config.schema
                });
                cDg = cDgtemp;
            });
        },


        /**
         * Export ps_report data in Excel file when render_type is table
         *当渲染类型为Table时，则调用Excel下载
         * @private
         */
        _onDownloadButtonClickedExcel: function () {
            var rows = this.model.psdata.report.rows;
            if (!rows[0].line_rows.length) {
                this.do_warn('下载错误', '请先选择条件并查询数据');

                return

            }

            function s2ab(s) {
                var buf = new ArrayBuffer(s.length);
                var view = new Uint8Array(buf);
                for (var i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xFF;
                return buf;
            }

            var workbook = XLSX.utils.book_new();

            for (var i = 0; i < rows.length; i++) {
                /***
                 * 存在多张表格下载，循环增加sheet
                 */
                var $document = document.getElementById('table_num' + i);
                var $head = document.getElementsByClassName('tableFloatingHeader')[0];
                var $headOriginal = document.getElementsByClassName('tableFloatingHeaderOriginal')[0];
                var sheet_name = rows[i].download_name[0] && rows[i].download_name[0].trim() ? rows[i].download_name : 'table' + i;
                if ($headOriginal === undefined) {
                    XLSX.utils.book_append_sheet(workbook, XLSX.utils.table_to_sheet($document), sheet_name);
                } else {
                    $document.removeChild($headOriginal);
                    XLSX.utils.book_append_sheet(workbook, XLSX.utils.table_to_sheet($document), sheet_name);
                    $document.insertBefore($headOriginal, $head);
                }
            }

            saveAs(new Blob([s2ab(XLSX.write(workbook, {
                bookType: 'xlsx',
                type: 'binary'
            }))], {type: "application/octet-stream"}), this.displayName + ".xlsx");

        },

        _onDownloadButtonClickedSheetJs: function (event) {
            if (!cDg || !cDg.data) {
                this.do_warn('下载错误', '请先选择条件并查询数据');
                return

            }
            if (!cDg) return;
            //获取后台定义的配置数据
            var config = this.model.psdata.report.config;
            //按照后台定义的列显示顺序打印行数据
            var headers = config.cols;
            var new_ws = XLSX.utils.json_to_sheet(cDg.data, {header: headers, skipHeader: true});
            //按照后台定义的合并单元格设置合并项
            if (!new_ws['!merges']) new_ws['!merges'] = [];
            new_ws['!merges'] = config.merges_define;
            new_ws['!cols'] = config.export_cols_define;
            var new_wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(new_wb, new_ws, config.export_file_name);

            XLSX.writeFile(new_wb, config.export_file_name + '.xlsx', {bookSST: true});
        },


        // sheetjs打印功能
        _onPrintButtonClickedTable: function (event) {


            $("#table-div").print(/*options*/);


        },

        // sheetjs打印功能
        _onPrintButtonClickedSheetJs: function (event) {
            if (!cDg || !cDg.data) {
                alert('请先选择条件并筛选数据');
            }
            if (!cDg) return;
            //获取后台定义的配置数据
            var config = this.model.psdata.report.config;
            //按照后台定义的列显示顺序打印行数据
            var headers = config.cols;
            var print_block = XLSX.utils.sheet_to_html(XLSX.utils.json_to_sheet(cDg.data, {
                header: headers,
                skipHeader: true
            }));
            $('#printSheetJs').css('display', 'block');
            $('#printSheetJs').html(print_block);
            //todo:需要前端人员重新修改样式

            $('#printSheetJs').find('table').css('border-collapse', 'collapse');
            $('#printSheetJs').find('td').css('border', '#000 1px solid');
            $('#printSheetJs').find('td').css('text-align', 'center');
            $("#printSheetJs").print(/*options*/);

            $('#printSheetJs').css('display', 'none');
            // $('#printSheetJs').html('');

        },


        /**
         * Open view when clicked on row
         *
         * @private
         * @param {OdooEvent} event
         */
        _onRowClicked: function (event) {
            if (event.data.act_model == 'account.move') {
                this.do_action({
                    type: 'ir.actions.act_window',
                    res_model: event.data.act_model,
                    views: [[false, 'form']],
                    res_id: event.data.domain,
                }, {clear_breadcrumbs: true});
            } else if (event.data.act_model == 'account.invoice') {
                this.do_action({
                    type: 'ir.actions.act_window',
                    res_model: event.data.act_model,
                    views: [[event.data.act_view, 'form']],
                    res_id: event.data.domain,
                }, {clear_breadcrumbs: true});
            } else if (event.data.act_model == 'account.payment') {
                this.do_action({
                    type: 'ir.actions.act_window',
                    res_model: event.data.act_model,
                    views: [[false, 'form']],
                    res_id: event.data.domain,
                }, {clear_breadcrumbs: true});
            } else {
                this.do_action({
                        type: 'ir.actions.act_window',
                        name: event.data.act_title,
                        res_model: event.data.act_model,
                        views: [[false, 'psreport']],
                        context: {'context_fields': event.data.domain},
                    }, {clear_breadcrumbs: true}
                );
            }

        },
    });

    return PsReportController;

});
